import { reqLogout, reqUserLogin } from "@/api";

const state = {
  userInfo: {
    // name: '',
    // token:''
    name: localStorage.getItem('name'),
    token: localStorage.getItem('token')
  }
}
const actions = {
  async userLogin({commit},user) {
    const result = await reqUserLogin(user)
    console.log('login',result)
    if (result.code === 200) {
      commit('SAVE_USER_INFO',result.data)
      return result.code
    } else {
      console.log(result.message)
    }
  },
  async userLogout({commit}){
    const result  = await reqLogout()
    console.log('logout',result);
    if(result.code === 200){
     // 清空本地存储
     localStorage.removeItem('name')
     localStorage.removeItem('token')
     
     commit('REMOVE_USER_INFO')

    }else{
      console.log(result.message);
    }
  }
}
const mutations = {
  SAVE_USER_INFO(state,userInfo) {
    state.userInfo.name = userInfo.name 
    state.userInfo.token = userInfo.token

    // 为了有一个更好的用户体验，在用户刷新页面的时候，也会有token
    // 此时可以在本地存储当中也存储一份
    localStorage.setItem('name', userInfo.name)
    localStorage.setItem('token',userInfo.token)
  },
  REMOVE_USER_INFO(state){
    state.userInfo.name = ''
    state.userInfo.token = ''
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}